<template>
    <div class="section-container qsBank-container">
        <div class="section-title">{{route.meta.title}}</div>
        <!-- <el-tabs v-model="curState" @tab-change="handleTabChange">
            <el-tab-pane v-for="item in tabArr" :key="item.bankType" :label="item.title" :name="item.bankType" />
        </el-tabs> -->
        <!-- 操作工具栏 -->
        <div class="section-actions">
            <div class="actions-left"> <!-- 左侧操作区 -->
                <el-button type="primary" @click="addGroup">添加分组</el-button>
                <SearchCmp v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleSearch" />
            </div>
        </div>
        <el-row class="content-box">
            <!-- 题库 -->
            <el-col :span="5" class="menu-tree-box">
                <div class="tree-header">
                    <span class="tree-header-title">题库分组</span>
                    <el-button type="primary" link @click="toggleExpand">{{ expandTree ? '全部收起' : '全部展开' }}</el-button>
                </div>
                <el-scrollbar max-height="calc(70vh - 51px)">
                    <el-tree
                    ref="treeRef"
                    :data="tabArr"
                    :props="defaultProps"
                    node-key="id"
                    :default-expand-all="expandTree"
                    class="tree-content"
                    @node-click="handleClickNode"
                    >
                        <template #default="{ node, data }">
                            <div class="custom-tree-node">
                                <div class="tree-node-label" :style="{ paddingLeft: (node.level - 1) * 10 + 'px' }" :title="node.label">
                                    <i class="iconfont">&#xe6a7;</i>
                                    {{ node.label }}
                                </div>
                                <div class="tree-num" v-if="node.isLeaf">
                                    （{{data.questionNum || 0}}题）
                                </div>
                                <div class="tree-options" v-if="data.canEdit">
                                    <el-dropdown>
                                        <i class="iconfont">&#xe78d;</i>
                                        <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item><el-button type="primary" link @click="addGroup(data)">新增</el-button></el-dropdown-item>
                                            <el-dropdown-item><el-button type="primary" link @click="editGroup(data)">编辑</el-button></el-dropdown-item>
                                            <el-dropdown-item><el-button type="primary" link @click="groupDelete(data)">删除</el-button></el-dropdown-item>
                                        </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </el-scrollbar>
            </el-col>
            <!-- 题目 -->
            <el-col :span="19" class="qs-table">
                <div class="user-table-top">
                    <div class="top-left">
                        <span class="curOStructure" v-if="curGroup">{{ curGroup.title }}</span>
                        <span class="user-default-show" v-else>未选择题库分组</span>
                        <span class="user-total">{{ `（${tableData?.length || 0}题）` }}</span>
                    </div>
                    <div class="top-right">
                        <el-button type="primary" size="small" @click="handleAddMyBankQs(curGroup)">添加题目</el-button>
                        <el-button size="small" @click="batchAddOpen = true">批量添加</el-button>
                    </div>
                </div>
                <div class="qs-list">
                    <RuifoxTable 
                    :loading="tableLoading" 
                    v-model:tableData="tableData" 
                    v-model:fieldList="fieldList"
                    :default-index="true" 
                    :default-checkbox="true" 
                        @handleSearch="handleSearch">
                        <template #default-checkbox="{ element }">
                            <div class="table-div-check">
                                <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size="" />
                            </div>
                        </template>
                        <template #compName="{ element }">
                            {{element.cmp.compName}}
                        </template>
                        <template #options="{ element }">
                            <div class="table-td-option unmover">
                                <el-button type="primary" link @click="handleEditMyBankQs(element.cmp,element.id)">编辑</el-button>
                                <el-button type="primary" link @click="handleDeleteMyBankQsByIds(element.cmp,element.id)">删除</el-button>
                                <el-dropdown>
                                    <span class="el-dropdown-link">
                                        <i class="iconfont">&#xe78d;</i>
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item @click="handleTransfer(element.id)">移动</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                        </template>
                    </RuifoxTable>
                </div>
                <PaginationView
                :total="queryData.total"
                :pageSize="queryData.pageSize"
                :currentPage="queryData.currentPage"
                :allChoose="isAllChooseBtn"
                :pageChoose="isPageChooseBtn"
                :checkedNum="checkedNum"
                :options="batchOptions"
                @changeSize="handleSizeChange"
                @currentChange="handleCurrentChange"
                @changePageChoose="handlePageChoose"
                @changeAllChoose="handleAllChoose"
                @cancelChoose="handleResetPagination"
                @invertChoose="handleInvertChoose"
                @refreshList="getTableData"
                @checkOption="handleBatchOptions"
                />
            </el-col>
        </el-row>
        <!-- 新增/修改分组 -->
        <el-dialog
            v-model="groupEditOpen"
            :title="`${groupTitle}分组`"
            width="30%"
        >
            <el-form 
            :model="formData" 
            label-width="auto" 
            style="max-width: 600px"
            :rules="rules"
            ref="ruleFormRef">
                <el-form-item label="上级分组" prop="pid">
                    <el-tree-select
                        v-model="formData.pid"
                        :data="groupList"
                        node-key="id"
                        check-strictly
                        default-expand-all
                        :render-after-expand="false"
                        :props="defaultProps"
                        placeholder="请选择上级团队，不选则为根目录"
                        style="width: 240px"
                    />
                </el-form-item>
                <el-form-item label="分组类型" prop="bankType">
                    <el-radio-group v-model="formData.bankType" :disabled="isBankTypeDisabled" >
                        <el-radio :label="2" style="margin-right: 10px;">非考试类</el-radio>
                        <el-radio :label="1">考试类</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="分组名称" prop="title">
                <el-input v-model="formData.title" style="width: 240px"></el-input>
                </el-form-item>
                <!-- <el-form-item label="是否可编辑" prop="canEdit">
                    <el-radio-group v-model="formData.canEdit">
                        <el-radio :label="true" style="margin-right: 10px;">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item> -->
            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="groupEditOpen = false">取消</el-button>
                <el-button type="primary" :disabled="groupLoading" @click="groupSubmit(ruleFormRef)">确定</el-button>
            </span>
            </template>
        </el-dialog>
        <!-- 添加/修改题目 -->
        <el-dialog
            v-model="myBankQsOpen"
            title=" 添加题目"
            align-center
            width="1480px"
            class="deal-bank-qs-dialog"
        >
            <div class="deal-bank-qs">
            <!-- 左 -->
            <div class="left-box">
                <div class="cmp-list">
                <div 
                    class="cmp-item" 
                    :class=" curCmpIndex == cmpIndex ? 'cmp-active' : ''" 
                    v-for="(cmp, cmpIndex) in componentList" 
                    :key="cmpIndex" 
                    @click="chooseCmp(cmp, cmpIndex)"
                >
                    <i class="iconfont">&#xe8b0;</i>
                    {{cmp.compName}}
                </div>
                </div>
            </div>
            <!-- 中 -->
            <div class="center-box">
                <el-form
                :label-position="'top'"
                :label-width="`40px`"
                :size="`default`"
                >
                <ul class="centerFormCmpS">
                    <draggable
                    class="dargCmpS"
                    :group="{ name: 'form' }"
                    :animation="300"
                    chosenClass="chosenClass"
                    dragClass="dragClass"
                    handle=".move-btn"
                    ghostClass="ghostClass"
                    :list="cmpList"
                    item-key="formItemId"
                    >
                    <template #item="{ element }">
                        <li
                        class="dragComponent active"
                        >
                        <form-cmp-ui :formComponent="element"></form-cmp-ui>
                        </li>
                    </template>
                    </draggable>
                </ul>
                </el-form>
            </div>
            <!-- 右 -->
            <div class="right-box">
                <form-config :formComponent="curCmp"/>
            </div>
            </div>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="myBankQsOpen = false">取消</el-button>
                <el-button type="primary" :disabled="myBankQsLoading" @click="myBankQsSubmit">确定</el-button>
            </span>
            </template>
        </el-dialog>
        <!-- 移动题目 -->
        <el-dialog v-model="transferDialog" title="选择题目分组" width="500px">
            <el-form>
              <el-form-item label="移动到" prop="pid">
                <el-tree-select
                  v-model="targetBankId"
                  :data="allBankList"
                  clearable
                  node-key="id"
                  :render-after-expand="false"
                  :props="treeProps"
                  placeholder="请选择目标分组"
                  style="width: 100%"
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="transferDialog = false">取消</el-button>
                <el-button type="primary" @click="transferConfirm">确定</el-button>
              </div>
            </template>
        </el-dialog>
         <!-- 批量添加试题 -->
        <el-dialog title="批量导入" v-model="batchAddOpen" width="48%" class="batch-dialog">
            <div class="batch-container">
              <div class="batch-step">
                <div class="step1 step-item">
                  <div class="step-item-left">
                    <div class="title">第一步：</div>
                    <div class="desc">将您的文档按照模板中的格式调整好</div>
                    <el-button type="primary" plain size="large" @click="handleDownloadTemp">下载Excel模板</el-button>
                  </div>
                  <div class="step-item-right">
                    <i class="iconfont">&#xe60d;</i>
                  </div>
                </div>
                <div class="step2 step-item">
                  <div class="step-item-left">
                    <div class="title">第二步：</div>
                    <div class="desc">调整好格式后，就开始上传文档吧</div>
                    <el-upload action="#" accept="xlxs" :show-file-list="false" :http-request="fileUpload">
                      <el-button type="primary" size="large">上传Excel模板</el-button>
                    </el-upload>
                  </div>
                  <div class="step-item-right">
                    <i class="iconfont">&#xe65c;</i>
                  </div>
                </div>
              </div>
              <div class="batch-desc">
                <p>格式说明：</p>
                <p>1、题型名称必须与表单中心提供题型名字一致，否则无法导入。</p>
                <p>2、导入的问题选项中，不要出现|符号。</p>
                <p>3、多选题的正确答案列中，以|作为分隔符。</p>
                <p>4、题型、题目必填，其余项可在批量导入后在编辑器中调整。</p>
              </div>
            </div>
            <template #footer>
              <span>
                <el-button @click="batchAddOpen = false">取消</el-button>
                <el-button type="primary" @click="batchAddOpen = false">确定</el-button>
              </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { useRoute } from 'vue-router'
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'
import {
  addMyBank,
  editMyBank,
  deleteMyBankByIds,
  selectBankQuestionPage,
  addMyBankQs,
  editMyBankQs,
  deleteMyBankQsByIds,
  updateBank,
  updateBankBatch,
  selectAllQuestion,
  insertQuestionBatch
} from "@/api/formDesign";
import { createTreeData } from '@ruifox-cms/utils'
import { tableList as mixTable } from '@ruifox-cms/utils'
import draggable from "vuedraggable";
import formCmpUi from "@/views/form/manage/design/formCmpUi.vue";
import formConfig from "@/views/form/manage/design/components/formCmpConfig.vue";
import * as XLSX from 'xlsx-js-style'

const route = useRoute()
const store = useStore()
// const formDesign = computed(()=>{return store.getters.formDesignInfo})
// const curState = ref(2)
const tabArr = ref([
  {id:-1,bankType:2,title:"非考试类",children:[]},
  {id:0,bankType:1,title:"考试类",children:[]}
])
const allBankList = ref([
  {id:-1,bankType:2,title:"非考试类",children:[]},
  {id:0,bankType:1,title:"考试类",children:[]}
])
const defaultProps = {
  children: 'children',
  label: function (data) {
    return data.title
  }
}
//获取我的题库
// const myBank = computed(()=>{return store.state.formDesignInfo.myBank})
const groupList = ref([{ id: 0, title: '根目录', children: [] }]) //添加分组
const handleGetMybank = () => {
  return new Promise((resolve) => {
    selectAllQuestion().then(res=>{
        tabArr.value.forEach(group => {
            group.children = [];
        });
        const treeData = createTreeData(res.data)
        // 将数据按 bankType 分类到对应组
        treeData.forEach(item => {
            const targetGroup = tabArr.value.find(
                group => group.bankType === item.bankType
            );
            if (targetGroup) {
                targetGroup.children.push(item);
            }
            const _targetGroup = allBankList.value.find(
                group => group.bankType === item.bankType
            );
            if (_targetGroup) {
                _targetGroup.children.push(item);
            }
        });
        // 创建新数组，包含根节点和原数据
        groupList.value[0].children = treeData
        resolve()
    })
  })
}
const loadData = async() => {
  try {
    // 等待题库获取完成
    await handleGetMybank();
    curGroup.value = tabArr.value[0].children[0]
    queryData.id = tabArr.value[0].children[0].id
    // 题库获取成功后，获取题目
    await getTableData();
  } catch (error) {
    // 错误处理
    console.error('数据加载失败:', error);
  }
};

// 调用加载函数
loadData();

//搜索题目
const searchCmpArray = ref([
  { label: '题目标题', key: 'keyWords' },
//   { label: '题目类型', key: 'itemIdList' },
//   { label: '难度等级', key: 'difficultyLevel' }
])
// 查找第一个children为空的对象
function findFirstEmptyChildren(data) {
    for (const item of data) {
        if (!item.children || item.children.length === 0) {
            return item;
        }
        if (item.children && item.children.length > 0) {
            const result = findFirstEmptyChildren(item.children);
            if (result) return result;
        }
    }
    return null;
}
// 修改搜索处理函数
const handleSearch = async() => {
    const res = await selectAllQuestion({keyWords:queryData.keyWords})
    tabArr.value.forEach(group => {
        group.children = [];
    });
    if(res.data.length > 0) {
        const treeData = createTreeData(res.data)
        // 将数据按 bankType 分类到对应组
        treeData.forEach(item => {
            const targetGroup = tabArr.value.find(
                group => group.bankType === item.bankType
            );
            if (targetGroup) {
                targetGroup.children.push(item);
            }
        });
        //先获取题目分组，再获取题目
        const firstEmptyChildren = findFirstEmptyChildren(treeData)
        curGroup.value = firstEmptyChildren
        queryData.id = firstEmptyChildren.id
        getTableData()
    }else {
        curGroup.value = null
        getTableData()
    }
}


// const handleTabChange = () => {
//     const matchedItem = tabArr.value.find(item => item.bankType === curState.value);
//     qsBankList.value = matchedItem.children
// }

const groupEditOpen = ref(false)
const groupLoading = ref(false)
const groupTitle = ref('新增') //1新增，2修改
const defaultForm = {
    bankType: 2,
    title: '',
    pid:null,
    canEdit:true,
    id:null
}
const formData = reactive(Object.assign({},defaultForm))
const ruleFormRef = ref(null)
const rules = reactive({
    title:[
        { required: true, message: '请输入分组名', trigger: 'blur' },
    ],
    bankType:[
        { required: true, message: '请选择分组类型', trigger: 'change' },
    ],
    pid:[
        { required: true, message: '请选择上级分组', trigger: 'change' },
    ],
    canEdit:[
        { required: true, message: '请选择是否可编辑', trigger: 'change' },
    ]
})
//父分组选择
// const handleChooseParent = (data) => {
//     formData.pid = data.id
// }
// 新增分组
const addGroup = (data) => {
    //获取默认表单的所有键
    const defaultKeys = new Set(Object.keys(defaultForm))
    for (const key in defaultForm) {
        formData[key] = defaultForm[key]
    }
    for (const key in formData) {
        if (!defaultKeys.has(key)) {
            delete formData[key]
        }
    }
  groupTitle.value = '新增'
  groupEditOpen.value = true
  isBankTypeDisabled.value = false
    isCascaderDisabled.value = false
  if(data) {
    // handleChooseParent(data)
    formData.pid = data.id
    formData.bankType = data.bankType
  }
}
// 修改分组
const isBankTypeDisabled = ref(false)
const isCascaderDisabled = ref(false)
const editGroup = (data) => {
    Object.assign(formData,data)
    groupTitle.value = '修改'
    groupEditOpen.value = true
    isBankTypeDisabled.value = true
    isCascaderDisabled.value = true
}

const groupSubmit = async(formEl) => {
    if (!formEl) return
    try {
        // 开始加载状态
        groupLoading.value = true
        // 验证表单
        const valid = await new Promise((resolve) => {
            formEl.validate((valid) => {
                resolve(valid)
            })
        })
        if (!valid) {
            groupLoading.value = false
            return
        }
        // 提交数据
        let res
        if (!formData.id) {
            res = await addMyBank(formData)
            if (res.code === 20000) {
                ElMessage({
                    showClose: true,
                    message: '新增成功！',
                    type: 'success'
                })
            } else {
                throw new Error(res.message || '新增失败')
            }
        } else {
            res = await editMyBank(formData)
            if (res.code === 20000) {
                ElMessage({
                    showClose: true,
                    message: '修改成功！',
                    type: 'success'
                })
            } else {
                throw new Error(res.message || '修改失败')
            }
        }
        // 刷新数据并关闭弹窗
        await handleGetMybank()
        groupEditOpen.value = false
    } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage({
            showClose: true,
            message: error.message || '提交失败，请重试',
            type: 'error'
        })
    } finally {
        // 无论成功失败都要关闭加载状态
        groupLoading.value = false
    }
}
const groupDelete = (data) => {
    let ids = []
    if(data){
        ids = [data.id]
    }
    ElMessageBox.confirm(
    '是否删除当前分组？清除后内容将无法恢复',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
        let res = await deleteMyBankByIds({ids})
        if(res.code == 20000){
            ElMessage({
                showClose: true,
                message: '删除成功！',
                type: 'success'
            })
            handleGetMybank()
        }
    })
}

const expandTree = ref(true)
const treeRef = ref(null);
const toggleExpand = () => {
    const nodes = treeRef.value.store.nodesMap
    const newExpandState = !expandTree.value
    Object.keys(nodes).forEach(key => {
        nodes[key].expanded = newExpandState
    })
    expandTree.value = newExpandState
};
//点击分组获取题目，只能点叶子节点
const {
  tableLoading,
  checkedList,
  isAllChooseBtn,
  isPageChooseBtn,
  isAllSearch,
  checkedNum,
  queryData,
  tableData,
  getTableData,
  // handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination
} = mixTable({
  getListApi: selectBankQuestionPage
})
const defaultQueryData = reactive({
  currentPage: 1,
  pageSize: 10,
  keyWords:"",
  id:null
})
Object.assign(queryData, defaultQueryData)

const curGroup = ref()
const handleClickNode = (data, node) => {
    if (data.id === -1 || data.id === 0) {
        return;
    }
    if (!node.isLeaf) return
    curGroup.value = data
    queryData.id = data.id
    handleResetPagination()
    getTableData()
    store.commit('formDesignInfo/SET_curBankType', data.bankType)
}
const fieldList = ref([
  { title: '题目标题', name: 'label' },
  { title: '类型', name: 'compName' },
  { title: '操作', name: 'options' }
])

// 获取所有组件列表
const fetchComponentList = async () => {
  try {
    await store.dispatch('formDesignInfo/handleGetComponentList');
    initComponentListObj();
  } catch (error) {
    console.error('获取组件列表失败:', error);
  }
};
fetchComponentList();

// 获取所有组件列表(去除分页器)
const componentList = computed(()=>{return store.state.formDesignInfo.componentList.filter(item=>item.type != 'pagenation')})
const myBankQsOpen = ref(false)
const myBankQsTitle = ref('添加')
const myBankQsLoading = ref(false)
const curCmp = ref()
const cmpList = ref([])
const curCmpIndex = ref(0)
const chooseCmp = (cmp, cmpIndex) => {
  let newCmp = JSON.parse(JSON.stringify(cmp))
  curCmpIndex.value = cmpIndex
  // 生成唯一id
  if (!newCmp.formItemId) newCmp.formItemId = newCmp.type + "_" + Date.now() + "_" + Math.ceil(Math.random() * 99999);
  if (!newCmp.labelIndex) newCmp.labelIndex = 1
  curCmp.value = newCmp
  cmpList.value = [newCmp]
}
// 添加题目
const handleAddMyBankQs = (val) => {
    if(val.id) {
        myBankQsTitle.value = '添加'
        curGroup.value = val
        chooseCmp(componentList.value[0], 0)
        myBankQsOpen.value = true
    }else {
        ElMessage({
            message: '请选择题目分组',
            type: 'warning',
        })
    }
}
//编辑题目
const handleEditMyBankQs = (val,id) => {
  myBankQsTitle.value = '修改'
  let index = componentList.value.findIndex(item=>item.type == val.type)
  val.id = id
  chooseCmp(val, index)
  myBankQsOpen.value = true
}
// 添加/修改题目确认
const myBankQsSubmit = async () => {
  myBankQsLoading.value = true
  // eslint-disable-next-line no-unused-vars
  let { formItemId, labelIndex , ...cmp} = cmpList.value[0]
  let param = { id: curGroup.value.id, cmp }
  try {
    if(!curCmp.value.id){
      let res = await addMyBankQs(param)
      if(res.code == 20000){
        ElMessage({
          showClose: true,
          message: '新增成功！',
          type: 'success'
        })
      }
    }else{
        param.id = curCmp.value.id
      let res = await editMyBankQs(param)
      if(res.code == 20000){
        ElMessage({
          showClose: true,
          message: '修改成功！',
          type: 'success'
        })
      }
    }
    // 刷新我的题库列表
    await getTableData()
    myBankQsOpen.value = false
  } catch (error) {
    console.error('保存题目失败:', error)
    ElMessage({
      showClose: true,
      message: '操作失败，请重试！',
      type: 'error'
    })
  } finally {
    myBankQsLoading.value = false
  }
}

// 删除题目
const handleDeleteMyBankQsByIds = (val,id) => {
  let ids = []
  if(val){
    ids = [id]
  }else{
    ids = checkedList.value;
  }
  ElMessageBox.confirm(
    '是否删除当前题目？清除后内容将无法恢复',
    '删除确认',
    {
        type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    }
  ).then(async () => {
    let res = await deleteMyBankQsByIds({ids})
    if(res.code == 20000){
      ElMessage({
        showClose: true,
        message: '删除成功！',
        type: 'success'
      })
      getTableData()
    }
  })
}
//移动题目
const targetBankId = ref(null)
const transferForm = ref({})
const transferDialog = ref(false)
const isBatch = ref(false)
const batchTransferForm = ref({})
const treeProps = {
    label: function (data) {
        return data.title
    },
    children: 'children',
    // 自定义 disabled 判断函数
    disabled: (node) => {
        // 当节点是"考试类"或"非考试类"且没有子节点时禁用
        return (node.id === -1 || node.id === 0) && 
            (!node.children || node.children.length === 0);
    }
};
const handleTransfer = (id) => {
    targetBankId.value = null
  transferDialog.value = true
  if(id) {
    isBatch.value = false
    transferForm.value.id = id
  }else {
    isBatch.value = true
  }
}

const transferConfirm = async () => {
  if (!targetBankId.value && targetBankId.value !== 0) {
    ElMessage.error('请选择要移动的题目分组')
  }
  let res
  if(isBatch.value) {
      //批量移动
      batchTransferForm.value.ids = checkedList.value
      batchTransferForm.value.isAllChoose = isAllSearch.value
      batchTransferForm.value.sourceBankId = curGroup.value.id
      batchTransferForm.value.targetBankId = targetBankId.value
    res = await updateBankBatch(batchTransferForm.value)
  }else {
    transferForm.value.bankId = targetBankId.value
    res = await updateBank(transferForm.value)
  }
    
  
  if (res.code === 20000) {
    ElMessage.success('移动成功')
    transferDialog.value = false
    getTableData()
  }
}

// 批量操作 
const batchOptions = ref([
  { name: "删除", value: "delete", icon: "&#xe74b;" },
  { name: "移动", value: "transfer", icon: "&#xe6eb;" },
]);
const handleBatchOptions = (data) => {
  if (data === "delete") {
    handleDeleteMyBankQsByIds()
  }  else if (data === "transfer") {
    handleTransfer()
  }
};

// 试题模板下载
const handleDownloadTemp = () => {
//   let baseApi = process.env.VUE_APP_BASE_API
  const a = document.createElement('a')
//   a.href = baseApi.replace('/admin_api', '') + '/hcs/doc/questionTemplate.xlsx'
  a.href = '/hcs/doc/questionTemplate.xlsx'
  a.download = '试题导入模板.xlsx'
  document.body.appendChild(a)
  a.click()
  setTimeout(() => {
    document.body.removeChild(a)
  }, 0)
}
// 批量添加题目
const componentListObj = ref()
const batchAddOpen = ref(false)
const initComponentListObj = () => {
  // 组件列表对象，以便读取excel后匹配组件
  componentListObj.value = componentList.value.reduce((acc, item) => {
    if (item.compName) {
      acc[item.compName] = item
    }
    return acc
  }, {})
}
// initComponentListObj()
const fileUpload = (e) => {
  let formList = []
  const file = e.file
  if (!file) return
  const reader = new FileReader()
  reader.onload = (e) => {
    const data = e.target.result
    const workbook = XLSX.read(data, { type: 'binary' })
    const sheetName = workbook.SheetNames[0]
    const sheet = workbook.Sheets[sheetName]
    const qsData = XLSX.utils.sheet_to_json(sheet, { raw: false })
    // 处理json数据
    qsData.forEach(item => {
      const {
        题型: compName,
        题目: label,
        题目描述: description,
        正确答案: referAnswer,
        答案解析: referAnalysis,
        分值: referScore
      } = item
      let tempComp = componentListObj.value[compName]
      
      if (tempComp) {
        let newCmp = JSON.parse(JSON.stringify(tempComp))
        newCmp.formItemId = newCmp.type + "_" + Date.now() + "_" + Math.ceil(Math.random() * 99999)
        label === undefined ? '' : newCmp.label = label
        referAnalysis === undefined ? '' : newCmp.referAnalysis = referAnalysis
        referScore === undefined ? '' : newCmp.referScore = Number(referScore)
        description === undefined ? '' : newCmp.description = description
        // 多选类型答案处理
        if(referAnswer !== undefined){
          if('checkbox|selectMultiple'.includes(newCmp.type)){
            newCmp.referAnswer = referAnswer.split('|')
          }else{
            newCmp.referAnswer = referAnswer
          }
        }
        // 选项处理(提取出属性名包含选项二字的属性值)
        const optionValues = Object.keys(item).filter(key => key.includes('选项'))
        if (optionValues.length) {
          newCmp.default = optionValues.map(key => {
            return {
              connect: [],
              label: item[key],
              optionFile: "",
              placeholder: key,
            }
          })
        }
        formList.push(newCmp)
        
      }
    })
    //加入题库
    insertQuestionBatch({bankId:curGroup.value.id,questionList:formList}).then(res => {
        if(res.code == 20000) {
            ElMessage({
                showClose: true,
                message: '批量添加成功！',
                type: 'success'
            })
            getTableData()
            batchAddOpen.value = false
        }
    })
  }
  reader.readAsBinaryString(file);
}
</script>
<style lang="scss" scoped>
.qsBank-container {
    .content-box {
        min-height: 70vh;
        border: 1px $borderColor solid;
        ::v-deep(.el-scrollbar__view) {
        height: 100%;
        }
        .menu-tree-box {
        overflow: hidden;
        border-right: 1px solid $borderColor;
        .custom-tree-node {
            display: flex;
        }
        .tree-header {
            height: 53px;
            background-color: $backBase;
            border-bottom: 1px solid $borderColor;
            padding: 0 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .tree-content {
            ::v-deep .el-tree-node .el-tree-node__content {
            border-bottom: 1px solid $borderColor;
            height: 48px;
            }
            ::v-deep .el-tree-node__label {
            width: 100%;
            .custom-tree-node {
                display: flex;
                justify-content: space-between;
                align-items: center;
                width: 100%;
                .tree-node-label {
                width: calc(100% - 16px - 26px);
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                }
                .tree-options {
                display: flex;
                padding-right: 10px;
                flex-shrink: 0;
                }
                .tree-num {
                    padding-right: 10px;
                }
            }
            }
        }
        }
        .qs-table {
        .user-table-top {
            padding: 15px;
            background: #dfe9f5;
            display: flex;
            justify-content: space-between;
            .top-left {
            .curOStructure {
                color: #666;
            }
            .user-default-show {
                color: #666;
            }
            .user-total {
                color: $mainColor;
            }
            }
        }
        }
    }
    .deal-bank-qs-dialog{
        ::v-deep(.el-dialog__body){
        padding: 0 20px !important;
        }
        // 新增/修改题目
        .deal-bank-qs{
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        width: 100%;
        height: 700px;
        .left-box{
            width: 280px;
            box-sizing: border-box;
            padding: 0 20px;
            padding-right: 40px;
            .cmp-list{
            .cmp-item{
                padding: 8px 10px;
                border: 1px solid #E5E5E5;
                border-radius: 5px;
                font-size: 14px;
                color: rgb(51, 51, 51);
                text-align: center;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                margin-bottom: 10px;
                cursor: pointer;
                .iconfont{
                margin-right: 5px;
                }
                &:hover{
                color: $mainColor;
                border: 1px solid $mainColor;
                background: $checkColor;
                .iconfont{
                    color: $mainColor;
                }
                }
            }
            .cmp-active{
                color: $mainColor;
                border: 1px solid $mainColor;
                background: $checkColor;
                .iconfont{
                color: $mainColor;
                }
            }
            }
        }
        .center-box{
            flex: 1;
            height: 100%;
            background: #F5F7FA;
            .dargCmpS {
            .dragComponent {
                box-sizing: border-box;
                background-color: #fff;
                padding: 10px 0;
                animation: slide-right 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) 1; // 移入
            }
            .active {
                position: relative;
                box-shadow: 0 0 10px rgba(0,0,0,0.2);
                &::before{
                position: absolute;
                content:'';
                left: 0;
                top: 0;
                width: 4px;
                height: 100%;
                background: $mainColor;
                }
            }
            ::v-deep .el-form-item__label {
                white-space: nowrap;
                padding-right: 0;
            }
            }
        }
        .right-box{
            width: 300px;
            box-sizing: border-box;
            padding: 0 20px;
        }
        }
    }
    .el-dialog.batch-dialog{
        .batch-container{
        padding: 0 20px;
        .batch-step{
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            .step-item{
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: calc((100% - 10px) / 2);
            box-sizing: border-box;
            padding: 20px;
            border: 1px solid #E8E8E8 ;
            .step-item-left{
                display: flex;
                flex-direction: column;
                margin-right: 20px;
                .title{
                font-size: 16px;
                font-weight: 600;
                margin-bottom: 10px;
                }
                .desc{
                font-size: 14px;
                color: #9C9C9C;
                margin-bottom: 10px;
                }
            }
            .step-item-right i{
                font-size: 100px;
                color: #cccccc;
            }
            }
            .step2{
            background: #f7f7f7;
            }
        }
        .batch-desc{
            font-size: 14px;
            color: #9C9C9C;
            p{
            margin-bottom: 4px;
            }
        }
        }
    }
}
</style>